package com.geping.etl.common.controller;

import com.geping.etl.common.entity.CmdTaskConfig;
import com.geping.etl.common.service.CmdTaskConfigService;
import com.geping.etl.common.service.LogsSynService;
import com.geping.etl.common.service.Sys_SubjectService;
import com.geping.etl.utils.EnvUitl;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 *  跑批程序控制器
 * @author liang.xu
 * @date 2021.7.23
 */
@RestController
public class PETLController {

	@Autowired
	private CmdTaskConfigService cmdTaskConfigService;

	@Autowired
	private LogsSynService LogsSynService;

	@Autowired
	private Sys_SubjectService ssr;

	@Value("${log.path}")
	private String dir;

	@RequestMapping(value = "/PETLRunUi", method = RequestMethod.GET)
	public ModelAndView PETLRunUi(HttpServletRequest request) {
		ModelAndView model = new ModelAndView();
		request.setAttribute("etlUrl", EnvUitl.props.getProperty("etl.server.url"));
		model.setViewName("common/etl");
		// List<Sys_Subject> list = ssr.findAllIdName();

		return model;
	}

	/*@RequestMapping(value = "/PsaveOrUpdatePETLEdit", method = RequestMethod.POST)
	public synchronized int PsaveOrUpdatePETLEdit(@RequestBody  TaskConfigAddOrUpdateDto taskConfigAddOrUpdateDto) {
		   cmdTaskConfigService.save(taskConfigAddOrUpdateDto);
		   return 1;
	}
*/

	@RequestMapping(value = "/PETLList", method = RequestMethod.POST)
	public  void PETLList(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String page = request.getParameter("page");           //获取页数
		String rows = request.getParameter("rows");           //获取每页显示的数据条数
		int pincPage = Integer.parseInt(page) - 1;             //页数从0开始
		int pincRows = Integer.parseInt(rows);
		String select = request.getParameter("select");
		List<CmdTaskConfig> pinlist = null;
		Specification<CmdTaskConfig> specification = new Specification<CmdTaskConfig>() {
			@Override
			public Predicate toPredicate(Root<CmdTaskConfig> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> preList = new ArrayList<>();
				if (StringUtils.isNotBlank(select)) {
					preList.add(cb.equal(root.get("subject"), select));
				}
				return cb.and(preList.toArray(new Predicate[preList.size()]));
			}
		};
		//使用pagerequest实现类，其中封装了分页所需要的信息
		PageRequest prs = new PageRequest(pincPage, pincRows);
		Page<CmdTaskConfig> gcPage = cmdTaskConfigService.findAll(specification, prs);
		pinlist = gcPage.getContent();
		JSONObject json = new JSONObject();
		PrintWriter out;
		try {
			out = response.getWriter();
			json.put("rows", pinlist);
			json.put("total", gcPage.getTotalElements()); // 将总页数传到页面上显示
			out.write(json.toString());
			if (out != null) {
				out.flush();
				out.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/*//删除
	@RequestMapping(value="/PETLDelete",method=RequestMethod.POST)
	public void PETLDelete(HttpServletRequest request,HttpServletResponse response){
		cmdTaskConfigService.deleteByIds(Collections.singletonList(request.getParameter("Ids").trim()));
	}*/
	// 删除
	@RequestMapping(value="/PETLDelete",method=RequestMethod.POST)
	public Object PETLDelete(String  ids){
		String[] split = ids.split(",");
		List<Integer> ids2 = new ArrayList<>();
		for (String s :split) {
			ids2.add(Integer.parseInt(s));
		}
		Map<String,Object> map = new HashMap<String,Object>();
		int n = cmdTaskConfigService.deleteByIds(ids2);
		if (n>0){
			map.put("code","0");
			map.put("msg","删除成功");
			map.put("data",n);
			return map;
		}else {
			map.put("code","1");
			map.put("msg","删除失败");
			map.put("data",null);
			return map;
		}

	}

	// 添加
	@RequestMapping(value="/PETLAdd",method=RequestMethod.POST)
	public int PETLAdd(CmdTaskConfig cmdTaskConfig){
		cmdTaskConfigService.save(cmdTaskConfig);
		return 1;
	}

	// 编辑
	@RequestMapping(value="/PETLEdit",method=RequestMethod.POST)
	public int PETLEdit(String name, String task, String odspath,String data_data, Integer id){
		cmdTaskConfigService.update(name,task,odspath,data_data,id);
		return 1;
	}

	// 下载日志
	@GetMapping("/DownloadLog")
	public void DownloadLog(HttpServletResponse response) {
		String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		String fileName = date + "_RunBatchLog.txt";
		String p = dir + File.separator + fileName;
		String path = p.replaceAll("\\\\", "/");
		File file = new File(path);
		byte[] b = new byte[1024];
		int len;
		try (InputStream in = new FileInputStream(file);
			 ServletOutputStream out = response.getOutputStream()){
			// 设置输出格式
			response.reset();
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
			// 循环取出流中的数据
			while ((len = in.read(b)) > 0) {
				out.write(b, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}